<template>
  <div>
    <van-form @submit="onSubmit">
      <van-field v-model="passWord"
                 name="passWord"
                 type="password"
                 label="密码"
                 placeholder="请输入密码"
      />
      <van-field v-model="again"
                 name="again"
                 type="password"
                 label="再次输入"
                 placeholder="请再次输入密码"
                 :rules="[{validator, message: '密码输入不一致'}]"
      />
      <div class="submit_button">
        <van-button :disabled="isDisabled" round block type="info" native-type="submit" class="button_main"
                    color="#7232DD">重设密码
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import qs from "querystring"
import {Form, Field, Button, Dialog, Toast} from "vant";
import {changeFindPassword, checkFindPasswordKey} from "@/api/user";

export default {
  name: "UpPassWord",
  components: {
    [Form.name]: Form,
    [Button.name]: Button,
    [Field.name]: Field,
    Toast,
    Dialog
  },
  data() {
    return {
      passWord: "",
      again: "",
      isDisabled: true,
    }
  },
  beforeUpdate() {
    this.isDisabled = this.passWord === "" || this.again === ""
  },
  created() {
    if (!this.$route.query.key) {
      this.$router.replace("/login")
    }
    this.checkKey(this.$route.query.key);
  },
  methods: {
    onSubmit(values) {
      changeFindPassword(qs.stringify({password: this.passWord, key: this.$route.query.key}))
        .then(res => {
          Dialog.alert({
            title: "修改成功",
            message: "修改成功，跳转登录页面"
          }).then(() => {
            this.$router.replace("/login");
          })
        })
        .catch(err => {

          Dialog.alert({
            title: "修改失败",
            message: err
          }).then(() => {
            this.$router.replace("/login");
          })
        })
    },

    checkKey(key) {
      checkFindPasswordKey({key}).catch(err => {
        Toast.fail("页面不存在");
        setTimeout(()=>{
          this.$router.replace("/login");
        }, 1000);
      })
    },

    validator(val) {
      return this.passWord === this.again
    }
  }
}
</script>

<style scoped>
.submit_button {
  padding: 20px 25px;
}
</style>
